const { Op } = require('sequelize');
const blogModel = require('../model/blogModel');
const blogTypeModel = require('../model/blogTypeModel');

module.exports.addBlogDao = async function (blog) {
  return await blogModel.create(blog)
}

module.exports.updateBlogDao = async function (id, blog) {
  await blogModel.update(blog, {
    where: {
      id
    }
  })
  return await blogModel.findByPk(id)
}

module.exports.delBlogDao = async function (id) {
  await blogModel.destroy({
    where: {
      id
    }
  })
}

module.exports.getBlogByIdDao = async function (id) {
  return await blogModel.findByPk(id)
}

module.exports.getBlogByPageDao = async function (query) {
  const { page, limit, keyword, categoryId } = query;

  const offset = (page - 1) * limit;
  const whereCondition = {
    title: {
      [Op.like]: `%${keyword}%`
    }
  };
  if (categoryId !== -1) {
    whereCondition.categoryId = categoryId;
  }

  return await blogModel.findAndCountAll({
    include: [
      {
        model: blogTypeModel,
        attributes: ['id', 'name'], 
        as: 'category'
      }
    ],
    where: whereCondition,
    offset,
    limit
  })
}

